package com.cari.oa.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.cari.oa.domain.AttachmentEntity;
import com.cari.oa.domain.SoftBugEntity;
import com.cari.oa.domain.SoftModuleEntity;
import com.cari.oa.domain.SoftProjectEntity;
import com.cari.oa.domain.SysDictItemEntity;
import com.cari.oa.service.AttachmentService;
import com.cari.oa.service.SoftBugService;
import com.cari.oa.service.SoftModuleService;
import com.cari.oa.service.SoftProjectService;
import com.cari.oa.service.SysDictItemService;
import com.cari.oa.service.SysUserService;
import com.cari.oa.util.Contants;
import com.cari.oa.util.StrUtils;
import com.cari.oa.util.Utils;

/**
* Title: SoftBugController
* Description:bugController
* Company: cari 
* @author  hjx 
* @date    2013-1-31
*/
@Controller
@SessionAttributes({"username","usercnname"})
public class SoftBugController  extends BaseDownloadController{

	@Resource
	private SoftBugService softBugService;
	@Resource
	private SysDictItemService sysDictItemService;
	@Resource
	private SoftProjectService softProjectService;
	@Resource
	private SysUserService sysUserService;
	@Resource
	private AttachmentService attachmentService;
	@Resource
	private SoftModuleService softModuleService;
	
	public static final String MODULE_NAME = "SOFT_BUG_MANAGE";
	
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(df, false));
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }
	
    @RequestMapping("soft/bug/list.do")
    public String list(@ModelAttribute("username") String username,String bugLevel, String expurgator,String status,String moduleId,String projectId, Integer curPage, ModelMap modelMap) {
        try {
			if(curPage == null) 
				curPage = 1;
			long totalRecords = 0;
			List<SoftProjectEntity>   projectList = softProjectService.getProjectListByEnname(username);
			SoftProjectEntity currProject = null;  //当前活动的项目
			List<SoftBugEntity> bugList = null;
			if(StrUtils.isEmpty(projectId) && projectList.size() > 0)
			{
				currProject = projectList.get(0);
				projectId = currProject.getId(); 
			}
			else
			{
				for(SoftProjectEntity curr : projectList)
				{
					if(curr.getId().equals(projectId))
					{
						currProject = curr;
						break;
					}
				}
			}
			List<Map<String,String>> userList = softProjectService.getUserByProjectId(projectId,null);
			boolean userCondition = true;
			for(Map<String,String> user : userList)
			{
				if(user.get("enname").equals(username) && user.get("type").equals("0"))//判断当前用户是否是开发人员
				{
					if(username.equals(currProject.getProjectManager()))
					{
						break;
					}
					userCondition = false;   //不显示查询条件中的【人员查询】(开发人员不显示)
					break;
				}
			}
			if(!userCondition)//开发人员
			{
			    bugList = softBugService.getPage( bugLevel, username,status,moduleId,projectId,"0", curPage, Contants.PAGE_SIZE);
			    totalRecords = softBugService.getCount( bugLevel, username, status, moduleId, projectId,"0");
			}
			else if(userCondition && projectList.size()>0)
			{
				
			    bugList = softBugService.getPage( bugLevel, expurgator,status,moduleId,projectId,"2", curPage, Contants.PAGE_SIZE);
			    totalRecords = softBugService.getCount( bugLevel, expurgator, status, moduleId, projectId,"2");
			}
			long totalPage = totalRecords / Contants.PAGE_SIZE + (totalRecords % Contants.PAGE_SIZE != 0 ? 1 : 0);
			List<SysDictItemEntity> bugLevelList = sysDictItemService.getItemsByGroupName("bugLevel");
			List<SysDictItemEntity> bugStatusList = sysDictItemService.getItemsByGroupName("bugStatus");
			List<SoftModuleEntity>  moduleList = softModuleService.getModuleByProjectId(projectId);
			modelMap.addAttribute("moduleList", moduleList);
			modelMap.addAttribute("userCondition", userCondition);
			modelMap.addAttribute("bugList", bugList);
			modelMap.addAttribute("bugLevelList", bugLevelList);
			modelMap.addAttribute("bugStatusList", bugStatusList);
			modelMap.addAttribute("projectList", projectList);
			modelMap.addAttribute("userList", userList);
			modelMap.addAttribute("curPage", curPage);
			modelMap.addAttribute("totalPage", totalPage);
			modelMap.addAttribute("totalRecords", totalRecords);
			modelMap.addAttribute("bugLevel", bugLevel);
			modelMap.addAttribute("expurgator", expurgator);
			modelMap.addAttribute("status", status);
			modelMap.addAttribute("moduleId", moduleId);
			modelMap.addAttribute("currProject", currProject);
		} catch (Exception e) {
			e.printStackTrace();
		}
        return "soft/bug/list";
    }
    
    @RequestMapping(value = "soft/bug/insert.do", method = RequestMethod.GET)
    public String enterInsert(String qs,String projectId, ModelMap modelMap) {
    	List<SysDictItemEntity> bugLevelList = sysDictItemService.getItemsByGroupName("bugLevel");
        List<SysDictItemEntity> bugStatusList = sysDictItemService.getItemsByGroupName("bugStatus");
        if(StrUtils.isNotEmpty(projectId))
        {
    	   SoftProjectEntity   project = softProjectService.getById(projectId);
    	   List<Map<String,String>> userList = softProjectService.getUserByProjectId(projectId,null);
    	   modelMap.addAttribute("project", project);
    	   modelMap.addAttribute("userList", userList);
        }
        List<String> treeList = softModuleService.getTree(true,projectId);      
       	modelMap.addAttribute("treeList", treeList);
        modelMap.addAttribute("bugLevelList", bugLevelList);
        modelMap.addAttribute("bugStatusList", bugStatusList);
        modelMap.addAttribute("qs", qs);
        return "soft/bug/insert";
    }
    
    @RequestMapping(value = "soft/bug/insert.do", method = RequestMethod.POST)
    @ResponseBody
    public String postInsert(@ModelAttribute("username") String username, @ModelAttribute("usercnname") String usercnname,@Valid SoftBugEntity softBugEntity, BindingResult result) {
        if(result.hasFieldErrors())
             return Utils.errorJsonResp(result.getFieldError().getDefaultMessage());
        if(softProjectService.getById(softBugEntity.getProjectId()).getStatus().equals("1"))
        	 return Utils.errorJsonResp("此项目已经停止使用不能为其添加bug信息！");
        if(softModuleService.getById(softBugEntity.getModuleId()).getStatus().equals("unable"))
           	return Utils.errorJsonResp("此模块已经停止使用不能为其添加bug信息！");
        softBugEntity.setSubEnname(username);
        softBugEntity.setSubCnname(usercnname);
        softBugEntity.setExpurgatorCn(sysUserService.getByEnname(softBugEntity.getExpurgator()).getCnname());
        softBugService.insert(softBugEntity);
        SysOperLogController.addOperLog(username, MODULE_NAME, "新增Bug" + softBugEntity.getTitle());
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("code", 1);
        resultMap.put("bugId", softBugEntity.getId());
        return JSON.toJSONString(resultMap);
    }
    
    @RequestMapping(value = "soft/bug/edit.do", method = RequestMethod.GET)
    public String enterEdit(@ModelAttribute("username") String username,String id,String projectId, String qs, ModelMap modelMap) {
    	List<SysDictItemEntity> bugLevelList = sysDictItemService.getItemsByGroupName("bugLevel");
        List<SysDictItemEntity> bugStatusList = sysDictItemService.getItemsByGroupName("bugStatus");
    	List<AttachmentEntity> attList = attachmentService.getByObjectId(id);
        SoftProjectEntity   project = null;
        List<Map<String,String>> selectedUserList = sysUserService.getUserAndRole(projectId); 
        SoftBugEntity     bug = softBugService.getById(id);
        List<String> types = new ArrayList<String>();
        if(StrUtils.isNotEmpty(projectId))
        {
    	   project = softProjectService.getById(projectId);
    	   List<Map<String,String>> userList = softProjectService.getUserByProjectId(projectId,null);
    	   modelMap.addAttribute("project", project);
    	   modelMap.addAttribute("userList", userList);
        }
        if(StrUtils.isNotEmpty(project.getProjectManager()) && project.getProjectManager().equals(username))
        {
        	types.add("3");
        }else{
	        for(Map<String,String> map : selectedUserList)
	        {
	        	if(map.get("enname").equals(username))
	        	{
	        		types.add(map.get("type"));
	        	}
	        }    
        }
        String[] pictureFormat = new String[]{"jpg" ,"jpeg" ,"gif","png" ,"bmp","tiff","pcx","tga","exif","fpx","svg","psd","cdr","pcd","dxf","ufo","eps","ai","raw"};
        List<String> pictureFormatList = Arrays.asList(pictureFormat);
        List<String> treeList = softModuleService.getTree(true,projectId);      
       	modelMap.addAttribute("treeList", treeList);
        modelMap.addAttribute("types",types);
        modelMap.addAttribute("attList", attList);
        modelMap.addAttribute("pictureFormatList", pictureFormatList);
        modelMap.addAttribute("bugLevelList", bugLevelList);
        modelMap.addAttribute("bug", bug);
        modelMap.addAttribute("bugStatusList", bugStatusList);
        modelMap.addAttribute("qs", qs);
        return "soft/bug/edit";
    }

    @RequestMapping(value = "/soft/bug/view.do", method = RequestMethod.GET)
    public String enterView(String id,String projectId, String qs, ModelMap modelMap) {
    	List<SysDictItemEntity> bugLevelList = sysDictItemService.getItemsByGroupName("bugLevel");
        List<SysDictItemEntity> bugStatusList = sysDictItemService.getItemsByGroupName("bugStatus");
    	List<AttachmentEntity> attList = attachmentService.getByObjectId(id);
        SoftBugEntity     bug = softBugService.getById(id);
        if(StrUtils.isNotEmpty(projectId))
        {
    	   SoftProjectEntity   project = softProjectService.getById(projectId);
    	   List<Map<String,String>> userList = softProjectService.getUserByProjectId(projectId,null);
    	   modelMap.addAttribute("project", project);
    	   modelMap.addAttribute("userList", userList);
        }
        String[] pictureFormat = new String[]{"jpg" ,"jpeg" ,"gif","png" ,"bmp","tiff","pcx","tga","exif","fpx","svg","psd","cdr","pcd","dxf","ufo","eps","ai","raw"};
        List<String> pictureFormatList = Arrays.asList(pictureFormat);
        List<SoftModuleEntity>  moduleList = softModuleService.getModuleByProjectId(projectId);
        modelMap.addAttribute("moduleList", moduleList);
        modelMap.addAttribute("attList", attList);
        modelMap.addAttribute("pictureFormatList", pictureFormatList);
        modelMap.addAttribute("bugLevelList", bugLevelList);
        modelMap.addAttribute("bug", bug);
        modelMap.addAttribute("bugStatusList", bugStatusList);
        modelMap.addAttribute("qs", qs);
        return "soft/bug/view";
    }
    
    @RequestMapping(value = "soft/bug/edit.do", method = RequestMethod.POST)
    @ResponseBody
    public String postEdit(@ModelAttribute("username") String username,@ModelAttribute("usercnname") String usercnname, 
    		@Valid SoftBugEntity softBugEntity, BindingResult result) {
        if(result.hasFieldErrors())
            return Utils.errorJsonResp(result.getFieldError().getDefaultMessage());
        softBugEntity.setExpurgatorCn(sysUserService.getByEnname(softBugEntity.getExpurgator()).getCnname());
        softBugEntity.setSubEnname(username);
        softBugEntity.setSubCnname(usercnname);
        softBugService.update(softBugEntity);
        SysOperLogController.addOperLog(username, MODULE_NAME, "修改Bug" + softBugEntity.getTitle());
        return Utils.normalJsonResp();
    }
    
    /**
     * Title: upload
     * Description:上传
     * @author    hjx 
     * @date       2013-3-13 
     * @param username
     * @param request
     * @param response
     * @param result
      */
 	@RequestMapping("soft/bug/upload.do")
 	public void upload(@ModelAttribute("usercnname") String username,HttpServletRequest request,HttpServletResponse response,BindingResult result) {
 		MultipartHttpServletRequest multipartRequest =(MultipartHttpServletRequest) request;
 		multipartRequest.setAttribute("ObjectType",AttachmentService.BUG_ATTACHEMENT_TYPE);
 		multipartRequest.setAttribute("ObjectId",multipartRequest.getParameter("bugId"));
 		super.upload(username, multipartRequest);
 	}
 	
 	/**
 	 * 下载
 	 */
 	@RequestMapping("soft/bug/download.do")
 	public void download(String fileName,String path,HttpServletRequest request, HttpServletResponse response) {
 		super.download(fileName, path, request, response);
 	}
 	
 	/**
	 * 删除文件
	 */
	@RequestMapping("soft/bug/deleteFile.do")
	@ResponseBody
    public String postDelete(@ModelAttribute("username") String username,HttpServletRequest request, String id,String path) {
		return super.postDelete(username, request, id, path);
    }
 	
}
